import React, { Component } from "react"
import PubSub from "pubsub-js"

import Username from "./username"
import Comment from "./comment"
import CommentList from "./commentList"
import "../index.css"

export default class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            username: "",
            context: "",
            commentList: [{ username: "ojj", context: "kwkwkwkw" }]
        }
    }
    componentDidMount() {
        PubSub.subscribe("addUsername", (msg, username) => { this.addUsername(username) });
        PubSub.subscribe("addContext", (msg, context) => { this.addContext(context) });
        PubSub.subscribe("delItem", (msg, index) => { this.delItem(index) });
    }

    addUsername = (val) => {
        this.setState({
            username: val
        })
    }
    addContext = (val) => {
        this.setState({
            context: val
        })
    }
    submitList = () => {
        const state = this.state
        //原数租
        let commentList = state.commentList
        //数据 
        let username = state.username
        let context = state.context

        if (!commentList) {
            commentList = [{ username: username, context: context }]
        } else {
            commentList.unshift({ username: username, context: context })
        }

        this.setState({
            commentList: commentList
        })
        // for (const iterator of commentList) {
        //     console.log(iterator);
        // }
    }
    clearAll = () => {
        this.setState({
            commentList: []
        })
    }
    delItem = (index) => {
        let { commentList } = this.state
        commentList.splice(index, 1)
        this.setState({ commentList })
    }
    render() {
        return (
            <div>
                <h1>请发表您的评论</h1>
                <div className="main_wrap">
                    <div className="left_wrap">
                        <Username></Username>
                        {/* <Username addUsername={this.addUsername}></Username>
                        <Comment addContext={this.addContext}></Comment> */}
                        <Comment></Comment>
                        <button onClick={this.submitList}>提交</button>
                    </div>
                    <div className="right_wrap">
                        <div>评论回复:</div> <button onClick={this.clearAll}>清空</button>
                        {/* <CommentList commentList={this.state.commentList} delItem={this.delItem}></CommentList> */}
                        <CommentList commentList={this.state.commentList}></CommentList>
                    </div>
                </div>
            </div>
        )
    }
}
